<?php

/**
 * @Author: liu
 * @Date:   2018-02-06 14:13:14
 * @Last Modified by:   liu
 * @Last Modified time: 2018-03-01 18:09:08
 * 门店的收货单
 */

class ScsPmsReceiveOrderController extends BaseController {

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-06T14:13:56+0800
     * @return   [type]                   [description]
     * 门店的收货单列表
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $status=Input::get("status");
            //$address=Input::get("address");
            $start_date = Input::get("start_date");
            $end_date = Input::get("end_date");
            $ordercode=Input::get("ordercode");
            $supplier=Input::get("supplier");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $pmso=DB::table("pms_receive_order")->leftJoin("maintenance_supplier","maintenance_supplier.id","=","pms_receive_order.supplier_id")->where("pms_receive_order.shop_id",$sc_user->shop_id);

            if($status != "") {
                $pmso->where("pms_receive_order.status",$status); //期望日期开始
            }  
//            if($address != "") {
//                $pmso->where("pms_receive_order.address","like",'%'.$address.'%'); //单号
//            }
            
            if ($start_date) $pmso->where("pms_receive_order.created_at",">=",$start_date." 00:00:00"); //创建时间范围开始
            if ($end_date) $pmso->where("pms_receive_order.created_at","<=",$end_date." 23:59:59"); //期望日期结束
            
            if($ordercode != "") {
                // $pmso->where("pms_order.hope_at",">",Input::get("hope_at_start")." 00:00:00"); //期望日期开始
                $pmso->whereRaw("CONCAT(IFNULL(pms_receive_order.plan_code,''),IFNULL(pms_receive_order.other_order_code,'')) like '%".$ordercode."%'" );
            }
            if($supplier != "") {
                $pmso->whereRaw("CONCAT(IFNULL(pms_receive_order.supplier_id,''),IFNULL(maintenance_supplier.name,'')) like '%".$supplier."%'" );
            }

            $count = $pmso->count();
            $pmso = $pmso->select("pms_receive_order.receive_code","pms_receive_order.plan_code","pms_receive_order.supplier_id","maintenance_supplier.name as supplier_name","maintenance_supplier.contacts_number","maintenance_supplier.contacts","pms_receive_order.other_order_code","pms_receive_order.address","pms_receive_order.all_num","pms_receive_order.ready_num","pms_receive_order.error_num","pms_receive_order.status","pms_receive_order.created_at")->orderBy("pms_receive_order.created_at","desc")->skip($page_size*($page-1))->take($page_size)->get();           

            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"receive_order_lists"=>$pmso,'status'=>PMSReceiveOrder::$status));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-06T17:55:02+0800
     * @return   [type]                   [description]
     * 收货单信息
     */
    public function receive_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $pmso=DB::table("pms_receive_order")->leftJoin("maintenance_supplier","maintenance_supplier.id","=","pms_receive_order.supplier_id")->where("pms_receive_order.plan_code",$plan_code)->where("pms_receive_order.shop_id",$sc_user->shop_id)->select("pms_receive_order.receive_code","pms_receive_order.plan_code","pms_receive_order.pay_type","pms_receive_order.supplier_id","maintenance_supplier.name as supplier_name","maintenance_supplier.contacts_number","maintenance_supplier.contacts","pms_receive_order.other_order_code","pms_receive_order.address","pms_receive_order.all_num","pms_receive_order.ready_num","pms_receive_order.error_num","pms_receive_order.status","pms_receive_order.logistics_freight","pms_receive_order.tax")->first();
            if(is_null($pmso)) {
                $response = Lang::get("scs_error.purchase_receive_order_notexit_65007");
                break;
            }

            //TODO 添加验证供应商信息变更  通过$plan_code  获取信息
            $pmso->all_tax_purchase_price = 0;
            $products = PMSReceiveProducts::where("receive_code",$pmso->receive_code)->get();
            foreach ($products as $v) {
                $pmso->all_tax_purchase_price += $v->all_num*$v->tax_purchase_price;
            }
            $pmso->all_tax_purchase_price = number_format($pmso->all_tax_purchase_price/100,2);
            $pmso->submit_at = PMSPlanOrder::get_submit_at($plan_code);//下单时间
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("receive_order_info"=>$pmso,'status'=>PMSReceiveOrder::$status));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "receive_detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-07T10:53:58+0800
     * @return   [type]                   [description]
     */
    public function receive_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $pro=PMSReceiveOrder::where("plan_code",$plan_code)->where("shop_id",$sc_user->shop_id)->first();
            if(is_null($pro)) {
                return Lang::get("scs_error.purchase_receive_order_notexit_65007");
            }
            if ($pro->status!=2&&$pro->status!=3) {//不是待收货或者已收货
                return Lang::get("scs_error.purchase_receive_order_status_65009");
            }            
            $prp=PMSReceiveProducts::where("receive_code",$pro->receive_code)->select("id","product_id","tax_purchase_price","no_tax_purchase_price","all_num","last_num")->get();
            $all_tax_purchase_price = 0;
            foreach ($prp as $_prp) {
                $si_info=SupplyItem::getCacheItemInfo($_prp->product_id);
                $_prp->tax_purchase_price=round($_prp->tax_purchase_price/100,2);
                $_prp->no_tax_purchase_price=round($_prp->no_tax_purchase_price/100,2);
                $_prp->item_id=$si_info->id;
                $_prp->item_type=$si_info->type;
                $_prp->code=$si_info->code;
                $_prp->old_code=$si_info->old_code;
                $_prp->brand_name=$si_info->brand_name;
                $_prp->series_name=$si_info->series_name;
                $_prp->model=$si_info->model;
                $_prp->unit=$si_info->unit;
                $_prp->bz_unit=$si_info->bz_unit;
                $_prp->volume_size=$si_info->pack;
                $_prp->item_name=$si_info->name;
                $_prp->all_tax_purchase_price=number_format($_prp->all_num*$_prp->tax_purchase_price,2);
                $all_tax_purchase_price += $_prp->all_num*$_prp->tax_purchase_price;

            }      
            $submit_at = PMSPlanOrder::get_submit_at($plan_code);//下单时间
            $response= array('code' => 0, 'msg' => 'ok', 'result' => array("receive_info"=>$prp,"type"=>PMSReceiveProductsResult::$sce_error_type,"submit_at"=>$submit_at,"all_tax_purchase_price"=>number_format($all_tax_purchase_price,2)));      
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "receive_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-07T10:53:58+0800
     * @return   [type]                   [description]
     * 异常处理接口
     * @link http://api.anhui.com/v1/scs/pmsreceiveorder/error_handle?token=ff7d5e3aef371ec4b9b02c5b066cc161&plan_code=15263523793328&type=2&args=[{"id":208,"product_id":235271,"number":1}]&is_create=1&desc=备注
     */
    public function error_handle(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
                'type'=>'required|in:1,2,3,4', //处理方式
                'args'=>'required', //[{"id":1,"product_id":1,"number":10}] 收货明细id和处理数量
                'is_create'=>'required',//是否新创建 采购单 0不 1创建
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            $type = Input::get('type');
            $args = Input::get('args');
            $desc=Input::get("desc");
            $is_create=Input::get("is_create");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $response = DB::transaction(function() use ($sc_user,$plan_code,$type,$desc,$args,$is_create){
                $pro=PMSReceiveOrder::where("plan_code",$plan_code)->where("shop_id",$sc_user->shop_id)->lockForUpdate()->first();

                if(is_null($pro)) {
                    return Lang::get("scs_error.purchase_receive_order_notexit_65007");
                }
                if ($pro->status!=2) {//不是待收货或者已收货
                    return Lang::get("scs_error.purchase_receive_order_status_65009");
                } 
                $ppo=PMSPlanOrder::find($pro->plan_code);//查找订货单 
                
                /**
                 * step 1 查询选定的处理的耗材
                 * @var [type]
                 */                
                $ids=$args?json_decode($args,1):array();
                $total_amount=0;
                $pms_code =Common::createOrderId(); //'采购单号',
                $temp_desc=strlen($desc)>0?$desc."，新生成采购单号：".$pms_code:"新生成采购单号：".$pms_code;
                $new_prpr_ids = []; // 需要更新的收货单id
                foreach ($ids as $_id) {
                    /**
                     * step 2 查找收货单详情  检查收货单未处理数量
                     * @var PMSPlanProducts
                     */
                    $prp=PMSReceiveProducts::find($_id["id"]);
                    if(is_null($prp)||$prp->receive_code!=$pro->receive_code) {
                        DB::rollback();
                        return Lang::get("scs_error.purchase_receive_order_product_notexit_65010");
                    }
                    if($prp->last_num<$_id["number"]) { //如果大于剩余可清点数量 则报错
                        DB::rollback();
                        return Lang::get("scs_error.purchase_receive_order_product_number_65011");
                    }
                    
                    /**
                     * step 3 生成处理清点记录
                     * @var PMSPlanProducts
                     */
                    $prpr=new PMSReceiveProductsResult();
                    $prpr->pms_receive_products_id=$prp->id;
                    $prpr->receive_code=$prp->receive_code;
                    $prpr->pms_code=$prp->pms_code;
                    $prpr->plan_code=$prp->plan_code;
                    $prpr->shop_id=$sc_user->shop_id;
                    $prpr->source=1;
                    $prpr->type=$type;
                    $prpr->num=$_id["number"];
                    $prpr->product_id=$prp->product_id;
                    $prpr->comment=$is_create==1?$temp_desc:$desc;
                    $prpr->created_type=1;
                    $prpr->created_by=$sc_user->id;  
                    $prpr->save();      
                    $new_prpr_ids[] =  $prpr->id;
                    /**
                     * step 4 处理收货单明细 和对应的  订货明细 采购详情，采购单状态
                     * @var PMSReceiveProducts
                     */
                    $total_amount=$total_amount+$_id["number"];
                    $prp->last_num=$prp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $prp->ready_num=$prp->ready_num+$_id["number"];
                    $prp->status=$prp->last_num==0?3:$prp->status;//如果已经清点完毕则 生成
                    $prp->save();                    
                    $ppp=PMSPlanProducts::find($prp->plan_products_id);//查找该订单 的订货单记录
                    $ppp->last_num=$ppp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $ppp->ready_num=$ppp->ready_num+$_id["number"];
                    $ppp->save(); 
                    
                    if($ppo->operation_type == 1){      //下单方式 (1:原有方式下单;2:门店询价下单;)
                        $pop=PMSOrderProducts::find($ppp->order_products_id);//查找采购单的采购需求
                        $pop->error_num=$pop->error_num+$_id["number"];//未满足数量也就是 异常处理数量加上清点数量
                        $pop->save(); 
                        $pmo=PMSOrder::find($pop->pms_code);//查找采购单
                        $pmo->error_num=$pmo->error_num+$_id["number"];//未满足数量也就是 异常处理数量加上清点数量
                        if(($pmo->right_num+$pmo->error_num)==$pmo->all_num){//如果已签收 +异常的于需求量也就是 已经处理完毕 订单状态完成
                            $pmo->status=6;//如果已经清点完毕则 采购单状态
                            $pms_order_flow = new PMSOrderFlow();
                            $pms_order_flow->pms_code = $pmo->pms_code;
                            $pms_order_flow->status =6;
                            $pms_order_flow->operation =8;
                            $pms_order_flow->created_by =$sc_user->id;
                            $pms_order_flow->created_type = 1;
                            $pms_order_flow->save();
                        }                    
                        $pmo->save();    
                    }
                }        
                /**
                 * step 4 处理收货单明细 和对应的  订货单  和采购单状态
                 * @var PMSReceiveProducts
                 */
                $pro->error_num=$pro->error_num+$total_amount;
                $pro->status=($pro->error_num+$pro->ready_num)==$pro->all_num?3:$pro->status;//如果已经清点完毕则 修改状态完毕
                $pro->save();
                
                //$ppo=PMSPlanOrder::find($pro->plan_code);//查找订货单
                $ppo->error_num=$ppo->error_num+$total_amount;//订货单的异常数据处理
                $ppo->status=($ppo->error_num+$ppo->ready_num)==$ppo->all_num?3:$ppo->status;//如果已经清点完毕则 修改状态完毕
                $ppo->save();
               
                /**
                 * step 5 如果生成采购单  则
                 * @var PMSReceiveProducts
                 */
                if($ppo->operation_type == 1){      //下单方式 (1:原有方式下单;2:门店询价下单;)
                    if($is_create==1){                      
                        $pms_order = new PMSOrder();
                        $pms_order ->pms_code = $pms_code;
                        $pms_order ->source = 1;
                        $pms_order ->created_by = $sc_user->id;
                        $pms_order ->created_type = 1;
                        $pms_order ->shop_id = $sc_user->shop_id;
                        $pms_order ->status = 1;
                        $pms_order ->type =$ppo->type;//类型和订货单采购类型一样
                        $pms_order->save();


                        $pms_order_flow = new PMSOrderFlow();
                        $pms_order_flow->pms_code = $pms_code;
                        $pms_order_flow->status =1;
                        $pms_order_flow->operation =1;
                        $pms_order_flow->created_by =$sc_user->id;
                        $pms_order_flow->created_type = 1;
                        $pms_order_flow->save();

                        $total_amount=0;
                        foreach ($ids as $_id) {

                            $pmsop=new PMSOrderProducts();
                            $pmsop->pms_code=$pms_code;
                            $pmsop->product_id=$_id["product_id"];
                            $pmsop->all_num=$_id["number"];
                            $pmsop->error_num=0;
                            $pmsop->status=1;
                            $pmsop->created_by = $sc_user->id;
                            $pmsop->created_type = 1;                
                            $pmsop->save();
                            $total_amount+=$_id["number"];
                        }        
                        foreach ($new_prpr_ids as $new_id) {
                           PMSReceiveProductsResult::where("id",$new_id)->update(array("new_code"=>$pms_code));     

                        }
                        PMSOrder::where("pms_code",$pms_code)->update(array("all_num"=>$total_amount));
                    }     
                } elseif ($ppo->operation_type == 2 && $ppo->status == 3) {  //下单方式 (1:原有方式下单;2:门店询价下单;)
                    $pms_code = '';     //门店询价下单 不生成采购单
                    //同步 经销商平台 订单状态
                    $ppoc = PMSPlanOrderContrast::where('plan_code', $plan_code)->first();
                    if($ppoc){
                        $change_order_res = GYSQueryPrice::changeOrder($ppoc->gys_plan_code);
                        if(empty($change_order_res)){
                            DB::rollback();
                            return Lang::get("scs_error.purchase_change_order_error_65013");
                        }
                    }
                }
                
                return array('code' => 0, 'msg' => 'ok', 'result' => array("plan_order_id"=>$plan_code,"pms_code"=>isset($pms_code)?$pms_code:""));
            });  
                
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "error_handle", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-08T09:57:01+0800
     * @return   [type]                   [description]
     * 入库检查
     */
    public function storage_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
                'args'=>'required', //[{"id":1,"number":10}] 收货明细id和处理数量
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            $args = Input::get('args');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $pro=PMSReceiveOrder::where("plan_code",$plan_code)->where("shop_id",$sc_user->shop_id)->first();
            if(is_null($pro)) {
                $response= Lang::get("scs_error.purchase_receive_order_notexit_65007");
                break;
            }            
            if ($pro->status!=2) {//不是待收货或者已收货
                $response= Lang::get("scs_error.purchase_receive_order_status_65009");
                break;
            }

            $ms=MaintenanceSupplier::find($pro->supplier_id);
            $payTaxFreight = MaintenanceSupplier::getPayTaxFreight($pro->supplier_id, $sc_user->shop_id, $response, $sc_user->shop->city_id);

            if (is_null($payTaxFreight)) {
                break;
            }

            $ids=$args?json_decode($args,1):array();
            $total_amount=0;
            $finally_arry=array();
            foreach ($ids as $_id) {
                $prp=PMSReceiveProducts::find($_id["id"]);
                if(is_null($prp)||$prp->receive_code!=$pro->receive_code) {
                    $response= Lang::get("scs_error.purchase_receive_order_product_notexit_65010");
                    break 2;
                }
                if($prp->last_num<$_id["number"]) { //如果大于剩余可清点数量 则报错
                    $response= Lang::get("scs_error.purchase_receive_order_product_number_65011");
                    break 2;
                }
                $temparr=array();
                $si_info=SupplyItem::getCacheItemInfo($prp->product_id);
                $temparr["id"]=$_id["id"];
                $temparr["item_id"]=$si_info->id;
                $temparr["item_type"]=$si_info->type;
                $temparr["code"]=$si_info->code;
                $temparr["item_name"]=$si_info->name;
                $temparr["tax_purchase_price"]=$prp->tax_purchase_price;
                $temparr["no_tax_purchase_price"]=$prp->no_tax_purchase_price;
                $temparr["number"]=$_id["number"];
                $sl=SupplyLocation::where('item_id',$prp->product_id)->where('shop_id',$sc_user->shop_id)->first();
                $temparr["location"]=isset($sl->location) ? $sl->location : "";

                $ss=SupplyStorage::where("origin_id",$si_info->id)->where("status",1)->orderBy("id","desc")->first();//暂时直接获取指定 耗材的最新转换关系 数据量小建议 数据量大 建议该表cache id 对应耗材关系
                if(isset($ss->data_id)){//如果存在转换关系  
                    $storage_si_info=SupplyItem::getCacheItemInfo($ss->data_id);
                    $temparr["storage_item_id"]=$storage_si_info->id;
                    $temparr["storage_item_type"]=$storage_si_info->type;
                    $temparr["storage_demand_quantity"]=$_id["number"]*$ss->num; //需要采购数量
                    $temparr["storage_tax_purchase_price"]=round($prp->tax_purchase_price/$ss->num,2);
                    $temparr["storage_no_tax_purchase_price"]=round($prp->tax_purchase_price/$ss->num,2);
                    $temparr["storage_code"]=$storage_si_info->code;
                    $temparr["storage_item_name"]=$storage_si_info->name;
                    $sl=SupplyLocation::where('item_id',$ss->data_id)->where('shop_id',$sc_user->shop_id)->first();
                    $temparr["storage_location"]=isset($sl->location) ? $sl->location : "";
                }else{
                    $temparr["storage_item_id"]=$temparr["item_id"];
                    $temparr["storage_item_type"]=$temparr["item_type"];
                    $temparr["storage_demand_quantity"]=$temparr["number"]; //需要采购数量
                    $temparr["storage_tax_purchase_price"]=$temparr["tax_purchase_price"];
                    $temparr["storage_no_tax_purchase_price"]=$temparr["no_tax_purchase_price"];
                    $temparr["storage_code"]=$temparr["code"];
                    $temparr["storage_item_name"]=$temparr["item_name"];
                    $temparr["storage_location"]=$temparr["location"];
                }
                $finally_arry[]=$temparr;
            }                   
            $response= array('code' => 0, 'msg' => 'ok', 'result' => array("storage_info"=>$finally_arry,"order_info"=>array('maintenance_supplier'=>$payTaxFreight->name,"pay_type"=>$payTaxFreight->regular_pay, 'tax' => $payTaxFreight->tax, 'id' => $payTaxFreight->id,'logistics_freight'=>$payTaxFreight->logistics_freight)));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "storage_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-08T12:51:07+0800
     * @return   [type]                   [description]
     * 入库的处理
     * @link http://api.anhui.com/v1/scs/pmsreceiveorder/storage_handle?token=ff7d5e3aef371ec4b9b02c5b066cc161&plan_code=15263523793328&args=[{"id":1,"number":1,storage_item_id":1,"storage_number":10,"tax_purchase_price":10,"no_tax_purchase_price":10,"location":"ccc"}]
     */
    public function storage_handle(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
                'tax' => 'required',//是否含税(1:含税;2:不含税;)
                'pay_type' => 'required',//结算方式  0现金  1挂账
                'logistics_freight' => 'required',//物流运费(1:含运费;2:不含运费;)
                'args'=>'required', //[{"id":1,"number":1,storage_item_id":1,"storage_number":10,"tax_purchase_price":10,"no_tax_purchase_price":10,"location":"ccc"}] 收货明细id和处理数量,入库耗材id，入库数量,货位
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.pms_perceive_order_canshu_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            $args = Input::get('args');
            //获取供应商最新的是否含税(新增)  物流运费(新增)  结算方式(修改)   S11.3  2018-9-14
            $pay_type = Input::get('pay_type');//0:现金;1:挂账;
            $tax = Input::get('tax');//是否含税  添加供应商是否含税  S11.3 添加2018-9-14
            $logistics_freight = Input::get('logistics_freight');// 添加供应商物流运费  S11.3 添加2018-9-14

            //判断三种方式是否配置
            if (!in_array($pay_type, [1, 0]) || !in_array($tax, [1, 2]) || !in_array($logistics_freight, [1, 2])) {
                $response = Lang::get('scs_error.maintenance_supplier_pay_tax_freight_error_130001');
                break;
            }
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $response = DB::transaction(function() use ($sc_user,$plan_code,$args, $pay_type, $tax, $logistics_freight){
                $pro=PMSReceiveOrder::where("plan_code",$plan_code)->where("shop_id",$sc_user->shop_id)->lockForUpdate()->first();
                if(is_null($pro)) {
                    return Lang::get("scs_error.purchase_receive_order_notexit_65007");
                }
                if ($pro->status!=2) {//不是待收货或者已收货
                    return Lang::get("scs_error.purchase_receive_order_status_65009");
                } 
                $ppo=PMSPlanOrder::find($pro->plan_code);//查找订货单

                /**
                 * step 1 生成入库单
                 * @var [type]
                 */
                $msl=new MaintenanceStorageList;
                $storage_list_id=Common::createId();
                $msl->id=$storage_list_id;
                $msl->shop_id=$sc_user->shop_id;
                $msl->date=date("Y-m-d",time());
                $msl->supplier=$pro->supplier_id;
                $msl->storage_type=0;//入库方式购入
                //$msl->pay_type=$pro->pay_type==0?0:2;//如果是现金或者挂
                $msl->pay_type=$pay_type==0?0:2;//如果是现金或者挂
                $msl->status=0;
                $msl->cust_id=$sc_user->id;
                $msl->type=1;
                $msl->desc="订货单：".$pro->plan_code."收货入库";
                $msl->create_by=$sc_user->id;
                $msl->tax = $tax;           //是否含税
                $msl->logistics_freight = $logistics_freight;       //物流运费
                $msl->save();
                $mdb=MainDateBase::where("shop_id",$sc_user->shop_id)->where("type",0)->first();
                if(is_null($mdb)){
                    MainDateBase::initDateShop($sc_user->shop_id);
                }
                /**
                 * step 2 查询选定的处理的耗材
                 * @var [type]
                 */                
                $ids=$args?json_decode($args,1):array();
                $total_amount=0;
                foreach ($ids as $_id) {
                    /**
                     * step 3 查找收货单详情  检查收货单未处理数量
                     * @var PMSPlanProducts
                     */
                    $prp=PMSReceiveProducts::find($_id["id"]);
                    if(is_null($prp)||$prp->receive_code!=$pro->receive_code) {
                        DB::rollback();
                        return Lang::get("scs_error.purchase_receive_order_product_notexit_65010");
                    }
                    if($prp->last_num<$_id["number"]) { //如果大于剩余可清点数量 则报错
                        DB::rollback();
                        return Lang::get("scs_error.purchase_receive_order_product_number_65011");
                    }
                    /**
                     * step 4 生成入库详情
                     * @var PMSPlanProducts
                     */
                    $dsi=SupplyItem::find($_id["storage_item_id"]);
                    if(is_null($dsi)||$dsi->status!=1){
                        DB::rollback();
                        $response= Lang::get("scs_error.purchase_supply_tiem_error_65012");
                        $response["msg"]="id为".$_id["id"].",".$response["msg"];
                        return $response;
                    }

                    $storage_item_info=SupplyItem::getCacheItemInfo($_id["storage_item_id"]);
                    $msi=new MaintenanceStorageItem;
                    $msi->list_id=$storage_list_id;
                    $msi->tax_purchase_price=$_id["tax_purchase_price"]*100;
                    $msi->no_tax_purchase_price=$_id["no_tax_purchase_price"]*100;
                    $msi->production_date=date("Y-m-d",time());
                    $msi->tax_plan_costs=0;
                    $msi->no_tax_plan_costs=0;
                    $msi->number=$_id["storage_number"];
                    $msi->tax_purchase_subtotal=$msi->tax_purchase_price*$msi->number;
                    $msi->current_number=$_id["storage_number"];
                    $msi->location=$_id["location"];
                    $msi->own_id=$sc_user->id;
                    $msi->data_id=$mdb->id;
                    $msi->item_type=$storage_item_info->type;
                    $msi->item_id=$storage_item_info->id;
                    $msi->pack_unit=$storage_item_info->pack;
                    $msi->shop_id=$sc_user->shop_id;
                    $msi->type=1;
                    $msi->status=0;
                    $msi->created_by=$sc_user->id;                    
                    $sl=SupplyLocation::where('item_id',$storage_item_info->id)->where('shop_id',$sc_user->shop_id)->first();
                    if($sl){
                        $sl->item_type=$storage_item_info->type;
                        $sl->location=$_id["location"];
                        $sl->save();
                    }else{
                        $sl=new SupplyLocation;
                        $sl->item_id=$storage_item_info->id;
                        $sl->item_type=$storage_item_info->type;
                        $sl->shop_id=$sc_user->shop_id;
                        $sl->location=$_id["location"];
                        $sl->save();
                    }
                    $msi->code=$storage_item_info->code;
                    $msi->name=$storage_item_info->name;
                    $msi->subject=$storage_item_info->st_classifi_id;
                    $msi->model=$storage_item_info->model;                
                    $msi->save();

                    /**
                     * step 5 生成处理清点记录
                     * @var PMSPlanProducts
                     */
                    $prpr=new PMSReceiveProductsResult();
                    $prpr->pms_receive_products_id=$prp->id;
                    $prpr->receive_code=$prp->receive_code;
                    $prpr->pms_code=$prp->pms_code;
                    $prpr->plan_code=$prp->plan_code;
                    $prpr->shop_id=$sc_user->shop_id;
                    $prpr->data_product_id=$storage_item_info->id;
                    $prpr->source=1;
                    $prpr->type=6;
                    $prpr->storage_num=$_id["storage_number"];
                    $prpr->num=$_id["number"];
                    $prpr->storage_list_id=$storage_list_id;
                    $prpr->storage_id=$msi->id;
                    $prpr->product_id=$prp->product_id;
                    $prpr->comment="入库单号：".$storage_list_id;
                    $prpr->new_code = $storage_list_id;
                    $prpr->created_type=1;
                    $prpr->created_by=$sc_user->id;  
                    $prpr->save();                    
                    /**
                     * step 6 处理收货单明细 和对应的  订货明细 采购详情，采购单状态
                     * @var PMSReceiveProducts
                     */
                    $total_amount=$total_amount+$_id["number"];
                    $prp->last_num=$prp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $prp->ready_num=$prp->ready_num+$_id["number"];
                    $prp->status=$prp->last_num==0?3:$prp->status;//如果已经清点完毕则 生成
                    $prp->save();                    
                    $ppp=PMSPlanProducts::find($prp->plan_products_id);//查找该订单 的订货单记录
                    $ppp->last_num=$ppp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $ppp->ready_num=$ppp->ready_num+$_id["number"];
                    $ppp->save(); 
                    
                    if($ppo->operation_type == 1){      //下单方式 (1:原有方式下单;2:门店询价下单;)
                        $pop=PMSOrderProducts::find($ppp->order_products_id);//查找采购单的采购需求
                        $pop->right_num=$pop->right_num+$_id["number"];//已收货数量加上清点数量
                        $pop->save(); 
                        $pmo=PMSOrder::find($pop->pms_code);//查找采购单
                        $pmo->right_num=$pmo->right_num+$_id["number"];//已收货数量加上清点数量
                        if(($pmo->right_num+$pmo->error_num)==$pmo->all_num){//如果已签收 +异常的于需求量也就是 已经处理完毕 订单状态完成
                            $pmo->status=6;//如果已经清点完毕则 采购单状态
                            $pms_order_flow = new PMSOrderFlow();
                            $pms_order_flow->pms_code = $pmo->pms_code;
                            $pms_order_flow->status =6;
                            $pms_order_flow->operation =8;
                            $pms_order_flow->created_by =$sc_user->id;
                            $pms_order_flow->created_type = 1;
                            $pms_order_flow->save();
                        }
                        $pmo->save();    
                    }
                }        
                /**
                 * step 7 处理收货单明细 和对应的  订货单  和采购单状态
                 * @var PMSReceiveProducts
                 */
                $pro->ready_num=$pro->ready_num+$total_amount;//签收数量
                $pro->status=($pro->error_num+$pro->ready_num)==$pro->all_num?3:$pro->status;//如果已经清点完毕则 修改状态完毕
                //如果该收货单已经结束怎修改收货单的最新信息
                if ($pro->status == 3) {
                    $pro->tax = $tax;               //是否含税      S11.3 2018-9-4 (添加)
                    $pro->pay_type = $pay_type;
                    $pro->logistics_freight = $logistics_freight;       //物流运费  S11.3 2018-9-4 (添加)
                }
                $pro->save();

                //$ppo=PMSPlanOrder::find($pro->plan_code);//查找订货单
                $ppo->ready_num=$ppo->ready_num+$total_amount;//签收数量
                $ppo->status=($ppo->error_num+$ppo->ready_num)==$ppo->all_num?3:$ppo->status;//如果已经清点完毕则 修改状态完毕
                $ppo->save();

                //同步 经销商平台 订单状态
                if ($ppo->operation_type == 2 && $pro->status == 3) {  //下单方式 (1:原有方式下单;2:门店询价下单;)
                    $ppoc = PMSPlanOrderContrast::where('plan_code', $plan_code)->first();
                    if($ppoc){
                        $change_order_res = GYSQueryPrice::changeOrder($ppoc->gys_plan_code);
                        if(empty($change_order_res)){
                            DB::rollback();
                            return Lang::get("scs_error.purchase_change_order_error_65013");
                        }
                    }
                } 
                
                /**
                 * step 8 执行入库操作
                 * @var PMSReceiveProducts
                 */
                $msl=MaintenanceStorageList::find($storage_list_id);             
                $response=MaintenanceStorageList::implement($msl,$sc_user->id);
                if($response["code"]==0){
                    return array('code' => 0, 'msg' => 'ok', 'result' => array("plan_order_id"=>$plan_code,"storage_list_id"=>$msl->id));
                }else{
                    return $response;
                }
            });                  
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "storage_handle", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-08T15:35:05+0800
     * @return   [type]                   [description]
     * 清点明细
     */
    public function receive_product_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $pro=PMSReceiveOrder::where("plan_code",$plan_code)->where("shop_id",$sc_user->shop_id)->first();
            if(is_null($pro)) {
                return Lang::get("scs_error.purchase_receive_order_notexit_65007");
            }
            if ($pro->status!=2&&$pro->status!=3) {//不是待收货或者已收货
                return Lang::get("scs_error.purchase_receive_order_status_65009");
            }  
            $pmspp=DB::table("pms_receive_products_result")->where("pms_receive_products_result.receive_code",$pro->receive_code);
            $pmspp=$pmspp->leftJoin("pms_receive_products","pms_receive_products.id","=","pms_receive_products_result.pms_receive_products_id")
                ->leftJoin("sc_user","pms_receive_products_result.created_by","=","sc_user.id")
                ->leftJoin("pms_user","pms_receive_products_result.created_by","=","pms_user.id")
                ->leftJoin("maintenance_storage_item","pms_receive_products_result.storage_id","=","maintenance_storage_item.id")
                ->select("pms_receive_products_result.num","pms_receive_products_result.storage_num","pms_receive_products_result.data_product_id","pms_receive_products_result.storage_list_id","pms_receive_products_result.product_id","pms_receive_products_result.comment","pms_receive_products_result.type","pms_receive_products_result.created_type","sc_user.real_name as ce_sce_name","pms_user.real_name as ce_pms_name","maintenance_storage_item.tax_purchase_price","pms_receive_products_result.new_code","pms_receive_products_result.created_at")->get();
            $item_info = [];
            foreach ($pmspp as $_pmspp) {
                $si_info=SupplyItem::getCacheItemInfo($_pmspp->product_id);
                $_pmspp->tax_purchase_price=round($_pmspp->tax_purchase_price/100,2);
                $_pmspp->item_id=$si_info->id;
                $_pmspp->item_type=$si_info->type;
                $_pmspp->code=$si_info->code;
                $_pmspp->old_code=$si_info->old_code;
                $_pmspp->unit=$si_info->unit;
                $_pmspp->bz_unit=$si_info->bz_unit;
                $_pmspp->volume_size=$si_info->pack;
                $_pmspp->item_name=$si_info->name;
                $storage_si_info=SupplyItem::getCacheItemInfo($_pmspp->data_product_id);
                $_pmspp->storage_item_id=isset($storage_si_info)?$storage_si_info->id:"";
                $_pmspp->storage_item_type=isset($storage_si_info)?$storage_si_info->type:"";
                $_pmspp->storage_code=isset($storage_si_info)?$storage_si_info->code:"";
                $_pmspp->storage_old_code=isset($storage_si_info)?$storage_si_info->old_code:"";
                $_pmspp->storage_unit=isset($storage_si_info)?$storage_si_info->unit:"";
                $_pmspp->storage_bz_unit=isset($storage_si_info)?$storage_si_info->bz_unit:"";
                $_pmspp->storage_volume_size=isset($storage_si_info)?$storage_si_info->pack:"";
                $_pmspp->storage_item_name=isset($storage_si_info)?$storage_si_info->name:"";
                $_pmspp->all_tax_purchase_price = number_format($_pmspp->storage_num*$_pmspp->tax_purchase_price,2);
                $new_code_key =  $_pmspp->created_at . $_pmspp->new_code; //同一时间，同一个单号为一条数据。如果没有生成新单号，按时间来判断是不是同时生成的
                if (isset($item_info[$new_code_key])) {
                    $item_info[$new_code_key]["list"][] = $_pmspp;
                }else{
                    $item_info[$new_code_key]['new_code'] = $_pmspp->new_code;
                    $item_info[$new_code_key]['type'] = $_pmspp->type;
                    $item_info[$new_code_key]["list"] = [$_pmspp];
                }
            }                   
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($pmspp),"item_info"=>  array_values($item_info),"type"=>PMSReceiveProductsResult::$type));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "pmsreceive_order", "event" => "receive_product_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Description  根据收货单中的plan_code 获取供应商相对于收货单是否更新了
     * @return string
     * @author yyc
     * @date 2018/9/17 11:37
     */
    public function supplierLastInfo()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user = $this->verificationSCSUserToken($token, $response);
            if (is_null($sc_user)) {
                break;
            }

            //获取订单信息
            $pro = PMSReceiveOrder::where("plan_code", $plan_code)->where("shop_id", $sc_user->shop_id)->first();

            if (is_null($pro)) {
                $response = Lang::get("scs_error.purchase_receive_order_notexit_65007");
                break;
            }

            //已经收货的收货单不需要给信息
            if ($pro->status == 3) {
                break;
            }

            //获取当前供货商最新的结算方式、物流运费、
            $payTaxFreight = MaintenanceSupplier::getPayTaxFreight($pro->supplier_id, $sc_user->shop_id, $response, $sc_user->shop->city_id);
            
            if (is_null($payTaxFreight)) {
                break;
            }

            $products = PMSReceiveProducts::where("receive_code",$pro->receive_code)->get();
            $pmsCode = array_unique(array_column($products->toArray(), 'pms_code'));
            $pms_code = $pmsCode[0];
            $cai_gou = PMSOrder::find($pms_code);

            //收货单和pms比较
            if ($pro->tax != $payTaxFreight->tax) {
                $tax = $pro->tax;
                $pro->tax = $payTaxFreight->tax == 555 ? $tax : $payTaxFreight->tax;
            }

            if ($pro->logistics_freight != $payTaxFreight->logistics_freight) {
                $logistics_freight = $pro->logistics_freight;
                $pro->logistics_freight = $payTaxFreight->logistics_freight == 555 ? $logistics_freight : $payTaxFreight->logistics_freight;
            }

            if ($pro->pay_type != $payTaxFreight->regular_pay) {

                $pay_type = $pro->pay_type;
                $pro->pay_type = $payTaxFreight->regular_pay == null ? $pay_type : $payTaxFreight->regular_pay;
            }

            //更新收货单三种方式信息
            try {
                $pro->save();
            } catch (Exception $e) {
                $response['result'] = Lang::get("scs_error.pms_perceive_order_canshu_error_21006");;
                break;
            }

            //三种方式只要有一种改变就返回信息   收货单和采购单比较弹出框

            if (is_null($cai_gou)) {
                break;
            }
            if ($cai_gou->logistics_freight != $pro->logistics_freight
                || $cai_gou->tax != $pro->tax
                || $cai_gou->regular_pay != $pro->pay_type
            ) {
                $response['result'] = [
                    'old' => [
                        'tax' => $cai_gou->tax,
                        'logistics_freight' => $cai_gou->logistics_freight,
                        'regular_pay' => $cai_gou->regular_pay,
                    ],
                    'new' => [
                        'tax' => $pro->tax,
                        'logistics_freight' => $pro->logistics_freight,
                        'regular_pay' => $pro->pay_type,
                    ],
                ];
                break;
            }

        } while (false);
        return json_encode($response);
    }
    
}